﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Com.Lancetinc.Evs.Helpers
{
    public static class UserHelper
    {
        public static bool CheckPassword(string password)
        {
            var encryptedPwd = GetRawEncryptedPassword(password);
            return !string.IsNullOrEmpty(encryptedPwd);
        }

        public static void ChangePassword(string oldPassowrd, string newPassword)
        {
            var encryptedPwd = GetRawEncryptedPassword(oldPassowrd);
            if (string.IsNullOrEmpty(encryptedPwd))
            {
                throw new ApplicationException("invalid password");
            }
            var newPwdMapping = GetNewPasswordMapping();

            var salt = Convert.ToChar('a' + Environment.TickCount % 26).ToString() + Convert.ToChar('a' + Environment.TickCount / 31 % 26).ToString();
            newPwdMapping[encryptedPwd] = salt + Md5Utils.Encrypt(salt + newPassword).Substring(10, 5);
            Properties.Settings.Default.Users = string.Join(";", newPwdMapping.Select(pair => pair.Key + ":" + pair.Value));
            Properties.Settings.Default.Save();
        }

        private static string GetRawEncryptedPassword(string password)
        {
            var lines = AppConfigHelper.LoadConfig(false);
            if (lines == null)
            {
                return null;
            }
            lines = lines.Where(line => line.StartsWith("p=") && line.Length == 9)
                .Select(line => line.Substring(2)).ToArray();

            var newPwdMapping = GetNewPasswordMapping();

            foreach (var line in lines)
            {
                var encryptedPwd = newPwdMapping.ContainsKey(line) ? newPwdMapping[line] : line;
                var md5 = Md5Utils.Encrypt(encryptedPwd.Substring(0, 2) + password);
                if (md5.Substring(10, 5) == encryptedPwd.Substring(2))
                {
                    return line;
                }
            }
            return null;
        }

        private static Dictionary<string, string> GetNewPasswordMapping()
        {
            var newPwdByOldPwd = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(Properties.Settings.Default.Users))
            {
                var newPwds = Properties.Settings.Default.Users.Split(';');
                foreach (var newPwd in newPwds)
                {
                    var ss = newPwd.Split(':');
                    if (ss.Length == 2)
                    {
                        newPwdByOldPwd[ss[0]] = ss[1];
                    }
                }
            }
            return newPwdByOldPwd;
        }
    }
}
